
package com.unionwo.commons.util;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 日期工具类
 * @author sunwuhua
 * 
 * 2012-02-06   sunwuhua    增加date2DateStr(Date date, String format)方法,日期串更灵活      
 * 2012-02-07   sunwuhua    增加 public String currentDateBefore(int n)方法
 *                              public String currentDateAfter(int n)方法
 *                          修改getCurrentTimeStr()方法为只获取当前时间，  getCurrentDateTimeStr()方法获取日期加时间   
 */
public final class DateUtil {

	private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";   // 默认时间格式
	
	
    /**
     * private constructor
     */
    private DateUtil() {// prevent instantiation
    }
    
    
    public static String date2DateStr(Date date) {
    	 return  date2DateStr(date, DEFAULT_DATE_FORMAT);
    }
    
    public static String date2DateStr(Date date, String format){
    	 SimpleDateFormat sdf = new SimpleDateFormat(format);
	      String dateString = sdf.format(date);
	      return dateString;
    }
     
    
    public static String getCurrentDateTimeStr() {
	      return  date2DateStr(new Date());
	}
	
	public static String getCurrentDateStr() {
		   return  getCurrentDateTimeStr().substring(0,10);
	}
	
	public static String getCurrentTimeStr(){
		return  getCurrentDateTimeStr().substring(10,19);
	}
	
	/*
    private static String  dateStrHelper(String dateFormat) {
    	  Date currentTime = new Date();		  
	      SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
	      String dateString = sdf.format(currentTime);
	      return dateString;
    }*/
    
	 // date string like '2010-01-22 00:00:00'
 	public static Timestamp dateStr2Timestamp(String dateString){
 		// 1. set date format 
 		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
 		// 2. parse date string
 		java.util.Date date = null;
 		try {
 			date= simpleDateFormat.parse(dateString);
 		}catch(ParseException ignored){}
 		// 3. get timestamp from date
 		Timestamp timestamp = new Timestamp(date.getTime());
 		return timestamp;
 	}
 	
 	public static Timestamp date2Timestamp(Date date) {
 		String dateStr = date2DateStr(date);
 		return dateStr2Timestamp(dateStr);
 	}
	
	
    public static Date getCurrentDate() {
       	// convert to specific style 
		
    	  Date currentTime = new Date();
	      SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
	      String dateString = sdf.format(currentTime);
	      java.util.Date currentTime_2 = sdf.parse(dateString,new ParsePosition(0));
	     	       	    
	      return currentTime_2;
	}
       
    public static Date timestamp2Date(Timestamp timestamp){
    	long milliseconds = timestamp.getTime() + (timestamp.getNanos() / 1000000);
        return new java.util.Date(milliseconds);

    }
    
    public static String timestamp2DateStr(Timestamp timestamp){
    	Date d = timestamp2Date(timestamp);
    	return date2DateStr(d);
    }
    
    
    
    /** fn-hd
     * rem: ���ڱȽ� s1��s2������� ��s2-s1 =?
     * par: s1,s2
     * ret: 
     */
    public static int compDate(String s1, String s2)
    {
               
        int day = 0;
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

        Date xxx1 = new Date();
        Date xxx2 = new Date();
        try
        {
            xxx1 = sf.parse(s1);
            xxx2 = sf.parse(s2);
            day = (int) ((xxx2.getTime() - xxx1.getTime()) / 3600 / 24 / 1000);
        }
        catch (ParseException e)
        {

            e.printStackTrace();
        }
        return day;

    } 
    
    /**
     * 计算当前时间之前n天的日期
     * @param n     天数
     * @return 
     */
    public static String currentDateBefore(int n){
    	 Calendar now = Calendar.getInstance();
    	 now.add(Calendar.DATE, -n);
         return now.get(Calendar.YEAR) +"-" + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DATE);
    }
    
       
    /**
     * 计算当前时间之后n天的日期
     * @param n  天数
     * @return
     */
    public static String currentDateAfter(int n) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.DATE, n);
        return now.get(Calendar.YEAR) +"-" + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DATE);
    }
  
    /**
	 * 
	 * @param datestr 日期字符串
	 * @param day  相对天数，为正数表示之后，为负数表示之前
	 * @return 指定日期字符串n天之前或者之后的日期
	 */
	public static String getBeforeAfterDate(String datestr, int day) {
		SimpleDateFormat df = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
		Date olddate = null;
		try {
			df.setLenient(false);
			olddate = new Date(df.parse(datestr).getTime());
		} catch (ParseException e) {
			throw new RuntimeException("日期转换错误");
		}
		Calendar cal = new GregorianCalendar();
		cal.setTime(olddate);
		cal.add(Calendar.DAY_OF_MONTH, day);
		Date date = new Date(cal.getTimeInMillis());
		
		return df.format(date);
	}
	public static String[] chaifen(String cn){
		
		Pattern pattern = Pattern.compile("[A-Z]+[0-9]{0,3}");
		Matcher mat = pattern.matcher(cn);
		mat.find();
		String str=mat.group();
		
		String s [] = new String[str.length()];
		for(int i=0;i<str.length();i++){
			s[i]=new String(str.substring(0, i+1));
		}
		return s;
	}
	/***
	 * 获取当月总共天数
	 * @return
	 */
	public static int getCurrentMonthLastDay(){
		Calendar c = Calendar.getInstance();
	
		c.set(Calendar.DATE, 1);//把日期设置为当月第一天
	
		c.roll(Calendar.DATE, -1);//日期回滚一天，也就是最后一天
	
		int maxDate = c.get(Calendar.DATE);
	
		return maxDate;

	}
	
	public static int getRestDayCurrentMonth(){
		int totalDay = getCurrentMonthLastDay();
		Calendar c = Calendar.getInstance();
		int day = c.get(Calendar.DAY_OF_MONTH);
		return totalDay - day + 1;
	}
    
	public static void main(String[] agrs) {
		System.out.println(getRestDayCurrentMonth());
		System.out.println("当前日期时间：" + DateUtil.getCurrentDateTimeStr());
		System.out.println("当前日期：" + DateUtil.getCurrentDateStr());
		System.out.println("当前时间：" + DateUtil.getCurrentTimeStr());
		System.out.println("14天后的日期：" + DateUtil.currentDateAfter(14));
		System.out.println("2天前的日期：" + DateUtil.currentDateBefore(2));
		System.out.println("��ǰʱ�䣺" + DateUtil.date2Timestamp(new Date()));
		System.out.println("��ǰʱ�䣺" + DateUtil.dateStr2Timestamp("2012-01-12 13:06:00"));
		System.out.println("��ǰʱ�䣺" + DateUtil.timestamp2Date( DateUtil.dateStr2Timestamp("2012-01-12 13:06:00")  ));
		System.out.println("��ǰʱ�䣺" + DateUtil.timestamp2DateStr( DateUtil.dateStr2Timestamp("2012-01-12 13:06:00")  ));
		   
	}

    
    
}
